package org.dxy.domain.handler.productionLine;

import com.google.common.eventbus.EventBus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.handler.CommandHandler;
import org.dxy.domain.port.repository.IProductionLineRepository;
import org.dxy.domain.port.repository.IWorkOrderRepository;
import org.dxy.domain.command.productionLine.RemoveWorkOrderFromLineCommand;
import org.dxy.domain.model.aggregate.ProductionLine;
import org.dxy.domain.model.aggregate.WorkOrder;
import org.dxy.types.common.CommandResult;
import org.springframework.stereotype.Component;

/**
 * @description: 移除工单从产线命令处理器
 * @author: dxy
 * @createTime: 2025/6/26 10:30
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RemoveWorkOrderFromLineCommandHandler implements CommandHandler<RemoveWorkOrderFromLineCommand, Void> {

    private final IProductionLineRepository productionLineRepository;
    private final IWorkOrderRepository workOrderRepository;
    private final EventBus eventBus;

    @Override
    public CommandResult<Void> handle(RemoveWorkOrderFromLineCommand command) {
        ProductionLine productionLine = productionLineRepository.findById(command.getLineId());
        if (productionLine == null) {
            log.error("未找到产线，command={}", command);
            return CommandResult.fail("产线不存在");
        }

        try {
            // 1. 从仓储加载产线聚合
            ProductionLine line = productionLineRepository.findById(command.getLineId());
            if (line == null) {
                log.error("未找到工位，command={}", command);
                return CommandResult.fail("工位不存在");
            }

            // 2. 加载工单实体
            WorkOrder workOrder = workOrderRepository.findById(command.getWorkOrderId());
            if (workOrder == null) {
                log.error("未找到工位，command={}", command);
                return CommandResult.fail("工位不存在");
            }

            // 3. 验证解绑参数
//            validateRemovalParameters(command, line, workOrder);

            // 4. 调用聚合根移除工单方法（内部会添加事件到事件列表）
            line.removeWorkOrder(command, workOrder);

            // 5. 持久化变更
            productionLineRepository.save(line);
            workOrderRepository.save(workOrder);

            // 6. 发布聚合产生的所有事件
            line.getDomainEvents().forEach(eventBus::post);

            // 7. 清理事件，防止重复发布
            line.clearDomainEvents();
            
            log.info("移除工单从产线成功, command={}", command);
            return CommandResult.success("移除工单从产线成功");
        } catch (IllegalStateException e) {
            log.warn("移除工单从产线失败，原因：{}", e.getMessage());
            return CommandResult.fail(e.getMessage());
        }
    }

//    private void validateRemovalParameters(RemoveWorkOrderFromLineCommand command,
//                                        ProductionLine line,
//                                        WorkOrder workOrder) {
//        // 验证解绑原因类型
//        if (command.getReasonType() == null || command.getReasonType().trim().isEmpty()) {
//            throw new IllegalArgumentException("解绑原因类型不能为空");
//        }
//
//        // 验证改派场景的目标产线
//        if ("REASSIGN".equals(command.getReasonType()) && command.getTargetLineId() == null) {
//            throw new IllegalArgumentException("改派场景必须指定目标产线");
//        }
//
//        // 验证工单是否属于该产线
//        if (!line.getAssignedWorkOrders().contains(workOrder.getWorkOrderId().getValue())) {
//            throw new IllegalArgumentException("工单未分配给当前产线");
//        }
//
////        // 验证运行中工单的解绑条件
////        if (workOrder.isInProgress() && !"EMERGENCY".equals(command.getReasonType())) {
////            throw new IllegalArgumentException("非紧急情况下不能解绑运行中的工单");
////        }
//    }
} 